package eu.irreality.dai.util;

import java.util.Iterator;

/**
 * Immutable class that represents a position (x,y) in a level.
 * 
 */
public class Position
{

    private int row;

    private int col;

    public Position(int row, int col)
    {
	this.row = row;
	this.col = col;
    }

    public Position(Position p)
    {
	this.row = p.getRow();
	this.col = p.getCol();
    }

    /*
     * public int getX() { return row; }
     * 
     * public int getY() { return col; }
     */

    public int getRow()
    {
	return row;
    }

    public int getCol()
    {
	return col;
    }

    @Override
    public boolean equals(Object obj)
    {
	if (obj != null && obj instanceof Position)
	{
	    Position pos = (Position) obj;
	    return (row == pos.getRow() && col == pos.getCol());
	}
	return false;
    }

    @Override
    public String toString()
    {
	return "(" + row + "," + col + ")";
    }

    /**
     * Returns whether this position is valid for a level of size (rows,cols).
     * 
     * @param rows
     * @param cols
     * @return
     */
    public boolean inRange(int rows, int cols)
    {
	return row < rows && col < cols && row >= 0 && col >= 0;
    }

    public Iterator<Position> adjacentPositions()
    {
	return new Iterator<Position>()
	{
	    int i = -1;
	    int j = -1;

	    public boolean hasNext()
	    {
		return (i < 1 || j < 1);
	    }

	    public Position next()
	    {
		if (j < 1)
		{
		    j++;
		} else
		{
		    j = -1;
		    i++;
		}
		return new Position(row + i, col + j);
	    }

	    @Override
	    public void remove()
	    {
		throw new UnsupportedOperationException();
	    }
	};
    }

    public Position move(Direction d)
    {
	return new Position(getRow() + d.getRowOffset(), getCol()
		+ d.getColOffset());
    }

}
